import os
import uuid
from typing import Tuple, Optional
from fastapi import UploadFile
import logging
from config.settings import config

logger = logging.getLogger(__name__)


class ImagePathManager:
    """统一管理图片路径的工具类"""

    def __init__(self, base_dir: str = None, web_prefix: str = None):
        """
        初始化图片路径管理器

        Args:
            base_dir: 图片存储的基础目录，默认从配置中读取
            web_prefix: Web访问路径前缀，默认从配置中读取
        """
        # 使用配置中的设置，如果提供了参数则覆盖配置
        self.base_dir = base_dir or config.IMAGE_STORAGE_DIR
        self.web_prefix = web_prefix or config.IMAGE_WEB_PREFIX

        # 确保目录存在
        os.makedirs(self.base_dir, exist_ok=True)

        logger.info(
            f"Image path manager initialized with base directory: {self.base_dir}"
        )
        logger.info(f"Web prefix: {self.web_prefix}")

    def get_full_path(self, filename: str) -> str:
        """
        获取文件的完整系统路径

        Args:
            filename: 文件名

        Returns:
            完整的文件系统路径
        """
        return os.path.join(self.base_dir, filename)

    def get_web_url(self, filename: str) -> str:
        """
        获取文件的Web访问URL

        Args:
            filename: 文件名

        Returns:
            Web访问URL
        """
        return f"{self.web_prefix}/{filename}"

    def generate_unique_filename(self, original_filename: str) -> str:
        """
        生成唯一的文件名

        Args:
            original_filename: 原始文件名

        Returns:
            唯一的文件名
        """
        if not original_filename:
            # 如果没有原始文件名，生成一个随机文件名
            return f"{uuid.uuid4()}.jpg"

        # 提取文件扩展名
        name, ext = os.path.splitext(original_filename)
        if not ext:
            ext = ".jpg"  # 默认扩展名

        # 生成唯一文件名：UUID_原文件名
        return f"{uuid.uuid4()}_{name}{ext}"

    def save_uploaded_file(self, file: UploadFile) -> Tuple[str, str]:
        """
        保存上传的文件

        Args:
            file: 上传的文件对象

        Returns:
            (文件名, 完整路径) 的元组
        """
        # 生成唯一文件名
        filename = self.generate_unique_filename(file.filename)
        full_path = self.get_full_path(filename)

        # 保存文件
        try:
            with open(full_path, "wb") as f:
                f.write(file.file.read())

            logger.info(f"File saved successfully: {full_path}")
            return filename, full_path

        except Exception as e:
            logger.error(f"Failed to save file {filename}: {e}")
            raise

    def get_file_info(self, filename: str) -> Tuple[str, str]:
        """
        获取文件信息

        Args:
            filename: 文件名

        Returns:
            (Web URL, 完整路径) 的元组
        """
        web_url = self.get_web_url(filename)
        full_path = self.get_full_path(filename)
        return web_url, full_path

    def file_exists(self, filename: str) -> bool:
        """
        检查文件是否存在

        Args:
            filename: 文件名

        Returns:
            文件是否存在
        """
        full_path = self.get_full_path(filename)
        return os.path.exists(full_path)

    def delete_file(self, filename: str) -> bool:
        """
        删除文件

        Args:
            filename: 文件名

        Returns:
            是否删除成功
        """
        try:
            full_path = self.get_full_path(filename)
            if os.path.exists(full_path):
                os.remove(full_path)
                logger.info(f"File deleted successfully: {full_path}")
                return True
            else:
                logger.warning(f"File not found for deletion: {full_path}")
                return False
        except Exception as e:
            logger.error(f"Failed to delete file {filename}: {e}")
            return False


# 创建全局实例，供整个项目使用
image_manager = ImagePathManager()
